package com.wwj.study.spring.formework.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

public class WAopProxyUtils {
    public static Object getTargetObject(Object proxy) throws Exception {
        if(!isProxy(proxy)){
            return proxy;
        }

        return getProxyTargetObject(proxy);
    }

    private static Object getProxyTargetObject(Object proxy) throws Exception {
        //获取代理对象的h属性  h属性存储的是代理工厂对象 创建代理对象的时候传入的。用于回调InvocationHandle.invoke
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        WAopProxy aopProxy = (WAopProxy) h.get(proxy);
        Field target = aopProxy.getClass().getDeclaredField("target");
        target.setAccessible(true);
        return target.get(aopProxy);
    }

    private static boolean isProxy(Object proxy) {
        return Proxy.isProxyClass(proxy.getClass());
    }


}
